<?php
namespace app\models;
/**
 * @desc 采购单model
 * @author liaojianwen
 * @date 2016-15-09
 */
use app\enum\EnumOther;
use app\dao\ProcurementDAO;
use app\dao\ProcurementDetailDAO;
use Yii;
use app\dao\PurchaseDAO;
use app\dao\SellDAO;
use app\dao\ProductUnitDAO;

class ProcurementModel extends BaseModel
{
	
	/**
	 * @desc 覆盖父方法返回对象
	 * @author liaojianwen
	 * @date 2016-12-09
	 * @return ProcurementModel
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}
	
	/**
	 * @desc 保存采购单
	 * @param [] $head 采购单头
	 * @param [] $detail 采购单明细
	 * @param [] $remove 删除明细
	 * @param int $id 采购单id
	 * @author liaojianwen
	 * @date 2016-12-12
	 */
	public function saveProcurement($head, $detail, $remove, $id)
	{
		if(empty($head)){
			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'head is empty' );
		}
		if (empty ( $detail )) {
			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'detail is empty' );
		}
		if(empty($id)){
			$id = 0;
		} else {
			$res_pur = PurchaseDAO::getInstance()->findByAttributes('procurement_id',"procurement_id =:pid and delete_flag=:fflag",[':pid' =>$id,':fflag' => EnumOther::NO_DELETE]);
			if($res_pur !=false){
				return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'exits next order');
			}
		}
		//清掉为空的元素
		foreach ($head as $k =>$hed){
			if(empty($hed)){
				unset($head[$k]);
			}
		}
		foreach ($detail as $k=> $det){
			foreach ($det as $j => $deet){
				if(empty($deet)){
					unset($detail[$k][$j]);
				}
			}
			if(!array_key_exists('base_unit', $detail[$k])){
				$unit = ProductUnitDAO::getInstance()->iselect("unit", "product_id =:pid and unit_type=:type", [':pid'=>$detail[$k]['goods_id'],':type'=> EnumOther::DEFAULT_UNIT],'one');
				if(!$unit){
					return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'no base_unit exist');
				}
				$detail[$k]['base_unit'] = $unit['unit'];
			}
		}
		// 表头信息
		$head ['procurement_date'] = strtotime ( $head ['procurement_date'] );
		$cond_head = "procurement_id =:id";
		$param_head = [
				':id' => $id
		];
		$Iid = ProcurementDAO::getInstance ()->ireplaceinto ( $head, $cond_head, $param_head, true );
		if (! $Iid) {
			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'save procurement_head failure' );
		}
		// 表单明细
// 		ProcurementDetailDAO::getInstance()->iupdate(['delete_flag' => EnumOther::DELETED], "procurement_id =:did", [':did'=>$Iid]);// 先删除后没有删除的数据更新回来
		
		//删除的明细
		foreach ($remove as $move){
			$res_remove = ProcurementDetailDAO::getInstance()->iupdate(['delete_flag'=>EnumOther::DELETED], "procurement_det_id = :det_id", [':det_id'=>$move['procurement_det_id']]);
			if(!$res_remove){
				$tr->rollBack();
				$this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'remove procurement_det_id:'+$move['procurement_det_id'] +'failed');
			}
		}
		foreach ( $detail as &$det ) {
			$det ['procurement_id'] = $Iid;
			$det ['delete_flag'] = EnumOther::NO_DELETE;
			$cond_det = "procurement_id = :id and procurement_det_id = :lid";
			$param_det = [
					':id' => $Iid,
					':lid' => isset($det ['procurement_det_id'])?$det['procurement_det_id']:0
			];
// 			$det['minus_quantity'] = $det['base_quantity'];
			$res_det = ProcurementDetailDAO::getInstance ()->ireplaceinto ( $det, $cond_det, $param_det, true );
			if (! $res_det) {
				return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'save procurement_detail failure' );
			}
		}
		
		return $this->handleApiFormat ( EnumOther::ACK_SUCCESS, '' );
	}
	
	/**
	 * @desc 获取采购单列表数据
	 * @param [] $pageInfo 页面/页码数据
	 * @param [] $condition 查询数据
	 * @author liaojianwen
	 * @date 2016-12-12
	 */
	public function getProcurements($pageInfo, $condition)
	{
		if(empty($pageInfo)){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','');
		}
		$result = ProcurementDAO::getInstance()->getProcurements($condition, $pageInfo);
		if(empty($result)){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','no data found');
		}
		return $this->handleApiFormat(EnumOther::ACK_SUCCESS,$result);
	}
	
	/**
	 * @desc 获取编辑状态下采购单的信息
	 * @param int $id  采购单单号
	 * @author liaojianwen
	 * @date 2016-12-12
	 */
	public function getProcurementInfo($id)
	{
		if(empty($id)){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','param is empty');
		}
		$pro_head = ProcurementDAO::getInstance()->getProcurementHead($id);
		if(empty($pro_head)){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','head data found');
		}
		$pro_det = ProcurementDetailDAO::getInstance()->getProcurementDet($id);
		if(empty($pro_det)){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','detail data found');
		}
		$result['head'] = $pro_head;
		$result['det'] = $pro_det;
		return $this->handleApiFormat(EnumOther::ACK_SUCCESS,$result);
	}

	/**
	 * @desc 删除采购单
	 * @author liaojianwen
	 * @date 2016-12-12
	 */
	public function delProcurement($ids)
	{
		if(empty($ids)){
			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'param is empty' );
		}
		$_ids = explode ( ',', $ids );
		
		$tT = Yii::$app->db->beginTransaction ();
		try {
			foreach ( $_ids as $id ) {
				$res_finish = ProcurementDAO::getInstance()->findByAttributes('finish_flag',"procurement_id=:id",[':id'=>$id]);
				if(isset($res_finish['finish_flag']) && $res_finish['finish_flag']){
					$tT->rollBack();
					return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','finish order can not be delete');
				}
				$res_procurement = ProcurementDAO::getInstance ()->updateByPk ( $id, ['delete_flag' => EnumOther::DELETED] );
				if(!$res_procurement){
					$tT->rollBack();
					return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'del_procurement fail');
				}
				//procurement_detail
				$procurement_det = ProcurementDetailDAO::getInstance()->iupdate(['delete_flag'=>EnumOther::DELETED], "procurement_id=:id", [':id'=>$id]);
				if(!$procurement_det){
					$tT->rollBack();
					return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','del_procurement_det fail');
				}
				$tT->commit();
				return $this->handleApiFormat(EnumOther::ACK_SUCCESS,'');
			}
		} catch ( \Exception $e ) {
			$tT->rollBack ();
			return false;
		}
	}
	
	/**
	 * 获取采购明细
	 * @author liaojianwen
	 * @date 2016-12-29
	 */
	public function getProcurementDet($id)
	{
		if (! $id) {
			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'param is empty' );
		}
		$fields = [
				'procurement_det_id',
				'd.procurement_id',
				'd.goods_id',
				'p.product_name',
				'p.product_sn',
				'd.quantity',
				'd.quantity_unit',
				'u.unit_name',
				'd.price',
				'd.amount',
				'd.remark',
				'd.minus_quantity',
				'd.received_quantity'
		];
	
		$joinArr = [
				[
						"product p",
						"p.product_id = d.goods_id"
				],
				[
						"unit u",
						"u.unit_id = d.quantity_unit",
						'left'=>''
				]
		];
		$conditions = "d.procurement_id = :id and d.delete_flag = :dflag";
		$params = [
				':id' => $id,
				':dflag' => EnumOther::NO_DELETE,
		];
		$result = ProcurementDetailDAO::getInstance()->iselect($fields, $conditions, $params, 'all',"procurement_det_id ASC", $joinArr,'d');
		if(empty($result)){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','no data found');
		}
		return $this->handleApiFormat(EnumOther::ACK_SUCCESS, $result);
	}
	
	/**
	 * @desc 查询销售订单（导入订单）
	 * @param $cond 查询条件
	 * @param $pageInfo 页面信息
	 * @author liaojianwen
	 * @date 2017-09-26
	 */
	public function selectSellOrder($cond, $pageInfo)
	{
		if(empty($pageInfo)){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','param is empty');
		}
		$result = SellDAO::getInstance()->selectSell($cond, $pageInfo);
		if(empty($result)){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','no data found');
		}
		return $this->handleApiFormat ( EnumOther::ACK_SUCCESS, $result );
	}
	
	/**
	 * @desc 检查订单是否被采购单占用
	 * @author liaojianwen
	 * @date 2017-09-26
	 */
	public function checkSellUsed($id)
	{
		if(!$id){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','param is empty');
		}
		$result = ProcurementDetailDAO::getInstance()->findByAttributes("procurement_det_id","sell_id = :pid and delete_flag =:flag",[
				':pid' => $id,
				':flag'=> EnumOther::NO_DELETE,
		]);
		if(empty($result)){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','');
		}
		return $this->handleApiFormat(EnumOther::ACK_SUCCESS,'');
	}
	
	/**
	 * @desc 采购订单明细
	 * @author liaojianwen
	 * @date 2017-09-27
	 */
	public function getExportProcurement($cond, $pageInfo, $filter)
	{
		if(empty($cond)){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'param is empty');
		}
		$result = ProcurementDAO::getInstance()->getExportProcurement($cond, $pageInfo, $filter);
		if(empty($result)){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'no data found');
		}
		
		return $this->handleApiFormat(EnumOther::ACK_SUCCESS, $result);
		
	}
	
	/**
	 * @desc 导出的订单明细
	 * @author liaojianwen
	 * @date 2017-09-28
	 */
	public function getExproInfo($condition)
	{
		if(empty($condition)){
			return false;
		}
		$result = ProcurementDAO::getInstance()->getExproInfo($condition);
		if(!$result)
			return false;
		return  $result;
	}

	/**
	 * @desc 导出采购订单商品
	 * @author liaojianwen
	 * @date 2017-09-28
	 */
	public function exportProInfo($proInfo, $filename, $title, $excVer = "xls")
	{
		$data = $proInfo;
		$objPHPExecl = new \PHPExcel();
		$objSheet = $objPHPExecl->getActiveSheet();
		$objWriter = NULL;
		// 创建文件格式写入对象实例
		switch ($excVer){
			case 'xlsx':
				$objWriter = new \PHPExcel_Writer_Excel2007($objPHPExecl);
				break;
			case 'xls':
				$objWriter = new \PHPExcel_Writer_Excel5($objPHPExecl);
				break;
			default:
				$objWriter = new \PHPExcel_Writer_Excel5($objPHPExecl);
		}
		//设置宽度
		$objSheet->mergeCells("A1:D2");
		$objSheet->setCellValue("A1", $title);
		$objSheet->getStyle('A1')->getFont()->setSize(26);
		$objSheet->getStyle('A1')->getFont()->setBold(true);
		$objSheet->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
			
			
		$objSheet->getColumnDimension('A')->setWidth(20);
		$objSheet->getColumnDimension('B')->setWidth(20);
		$objSheet->getColumnDimension('C')->setWidth(20);
		$objSheet->getColumnDimension('D')->setWidth(20);
// 		$objSheet->getColumnDimension('E')->setWidth(20);
		
		$objSheet->setCellValue('A3', '供应商');
		$objSheet->getStyle('A3')->getFont()->setBold(true);
		$objSheet->setCellValue('B3', '产品名称');
		$objSheet->getStyle('B3')->getFont()->setBold(true);
		$objSheet->setCellValue('C3', '单位');
		$objSheet->getStyle('C3')->getFont()->setBold(true);
		$objSheet->setCellValue('D3', '数量');
		$objSheet->getStyle('D3')->getFont()->setBold(true);
// 		$objSheet->setCellValue('E3', '单价');
// 		$objSheet->getStyle('E3')->getFont()->setBold(true);
		
		$rowNum = 4;
		foreach($data as $det){
			$this->_genExcelFont($objSheet, "A".$rowNum, "A".$rowNum, $det['supplier_name'], false);
			$this->_genExcelFont($objSheet, "B".$rowNum, "B".$rowNum, $det['product_name'], false);
			$this->_genExcelFont($objSheet, "C".$rowNum, "C".$rowNum, $det['unit_name'], false);
			$this->_genExcelFont($objSheet, "D".$rowNum, "D".$rowNum, $det['base_quantity'], false);
// 			$this->_genExcelFont($objSheet, "E".$rowNum, "E".$rowNum, $det['price'], false);
		
			$rowNum++;
		}
			
		ob_end_clean(); // 去掉缓存
		header("Content-Type: application/force-download");
		header("Content-Type: application/octet-stream");
		header("Content-Type: application/download");
		header('Content-Disposition:inline;filename="' . $filename . '.xls"');
		header("Content-Transfer-Encoding: binary");
		header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
		header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header("Pragma: no-cache");
		$objWriter->save('php://output');
	}
}
